//
//  BindCardNextViewController.m
//  PlayBall
//
//  Created by Edward Zhang on 12-5-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "JddBindCardNextViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "JddViewControllerManager.h"

@interface JddBindCardNextViewController ()

@end

@implementation JddBindCardNextViewController

@synthesize cardInfoPickerView;
@synthesize bgScrollView;
@synthesize cardNumberTextField;
@synthesize selectBankTableView;

@synthesize cardOwnerLabel;
@synthesize province;
@synthesize city;
@synthesize bank;
@synthesize branchBank;
@synthesize okButton;
@synthesize bankId;
SHARED_VIEW_CONTROLLER_IMPLEMENT(JddBindCardNextViewController);

- (void)QueryBindCardOperationResult:(NSData *)result{ 
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result) {
        if ([JddDataParser parseBindCardResult:result]) {
            [JddUserProfile sharedInstance].BankCardNumber = cardNumberTextField.text;
            [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
            [[JddViewControllerManager sharedInstance] popToBackViewController];
        } else {
            [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
        }
 
    }else{
        [JddCommonFunction messageBoxWithMessage:@"网络堵塞，请重试！"];
        [[JddViewControllerManager sharedInstance] popToBackViewController];
    }
}

- (IBAction)bindButtonClicked:(id)sender{
    if ([self.realityName.text length]==0||self.realityName.text == nil) {
        [JddCommonFunction messageBoxWithMessage:@"请输入持卡人姓名"];
    }
    else if ([cardNumberTextField.text length]==0||cardNumberTextField.text == nil) {
        [JddCommonFunction messageBoxWithMessage:@"请输入银行卡号"];
    }else {
    if ([self.province length]==0|| self.province == nil||!provinceSelected) {
        [JddCommonFunction messageBoxWithMessage:PLEASE_SELECT_PROVINCE];
    }
    else if ([self.city length]==0|| self.city == nil||!citySelected) {
        [JddCommonFunction messageBoxWithMessage:PLEASE_SELECT_CITY];
    }
     else if ([self.bank length]==0|| self.bank == nil||!bankSelected) {
        [JddCommonFunction messageBoxWithMessage:PLEASE_SELECT_BANK];
     } else{
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
    
    JddBindCardOperation *operation = [[JddBindCardOperation alloc] init];
    operation.province = self.province;
    operation.city = self.city;
    operation.bank = self.bank;
    operation.bankId = bankId;
    operation.cardNumber = self.cardNumberTextField.text;
         operation.realityName = self.realityName.text;
    operation.delegate = self;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
     }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 36.0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;
    
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                                   reuseIdentifier:[NSString stringWithFormat:@"%d", pickerViewMode]];
    cell.textLabel.font = [JddCommonFunction jddFont];
    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = @"1.选择省份";
            break;
        case 1:
            cell.textLabel.text = @"2.选择城市";
            break;
        case 2:
            cell.textLabel.text = @"3.选择银行";
            break;
//        case 3:
//            cell.textLabel.text = @"4.请选择支行";
//            break;
        default:
            break;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:
            [self provinceButtonClicked:nil];
            break;
        case 1:
            [self cityButtonClicked:nil];
            break;
        case 2:
            [self bankButtonClicked:nil];
            break;
//        case 3:
//            [self branchBankButtonClicked:nil];
//            break;
        default:
            break;
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)QueryProviceListOperationResult:(NSData *)result{
    if (result) {
        [cardInfoPickerView.activityIndicatorView setHidden:YES];
        
        if ([provinceArray count]) {
            [provinceArray removeAllObjects];
        }
        if ([JddDataParser parseProvinceListResult:result provinceArray:provinceArray]) {
            [cardInfoPickerView.pickerView reloadComponent:0];
        }
    }
}

- (IBAction)provinceButtonClicked:(id)sender{
    
    pickerViewMode = PICKERVIEW_MODE_PROVINCE;
    
    JddQueryProviceListOperation *operation = [[JddQueryProviceListOperation alloc] init];
    operation.delegate = self;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    
    [self setJddPickerViewHidden:NO];
    [cardInfoPickerView.activityIndicatorView setHidden:NO];
    [cardInfoPickerView.activityIndicatorView startAnimating];
//    //    ###########################################
//    [cardInfoPickerView.pickerView selectRow:0 inComponent:0 animated:YES];

}

- (void)QueryCityListOperationResult:(NSData *)result{
    if (result) {
        [cardInfoPickerView.activityIndicatorView setHidden:YES];
        
        cityDictionary = [NSMutableArray arrayWithArray:[JddDataParser parseCityListResult:result province:province cityDictionary:cityDictionary]];
            [cardInfoPickerView.pickerView reloadComponent:0];
        }
}

- (IBAction)cityButtonClicked:(id)sender{
    if (!provinceSelected) {
        [JddCommonFunction messageBoxWithMessage:PLEASE_SELECT_PROVINCE];
        return;
    }
    pickerViewMode = PICKERVIEW_MODE_CITY;

    JddQueryCityListOperation *operation = [[JddQueryCityListOperation alloc] init];
    operation.delegate = self;
    operation.province = [selectBankTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]].textLabel.tag;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    
    [self setJddPickerViewHidden:NO];
    [cardInfoPickerView.activityIndicatorView setHidden:NO];
    [cardInfoPickerView.activityIndicatorView startAnimating];
//    //    ###########################################
//    [cardInfoPickerView.pickerView selectRow:0 inComponent:0 animated:YES];

}

- (void)QueryBranchBankListOperationResult:(NSData *)result{
    if (result) {
        [cardInfoPickerView.activityIndicatorView setHidden:YES];
        
        if ([JddDataParser parseBranchBankListResult:result branchBankArray:branchBankArray]) {
            [cardInfoPickerView.pickerView reloadComponent:0];
        } else {
            [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
            [self setJddPickerViewHidden:YES];
        }
    }    
}

- (IBAction)branchBankButtonClicked:(id)sender{
    pickerViewMode = PICKERVIEW_MODE_BRANCH_BANK;
    
    if (!bankSelected) {
        [JddCommonFunction messageBoxWithMessage:PLEASE_SELECT_BANK];
        return;
    }
    
    JddQueryBranchBankListOperation *operation = [[JddQueryBranchBankListOperation alloc] init];
    operation.delegate = self;
    operation.city = [selectBankTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]].textLabel.text;
    operation.bank = [selectBankTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]].textLabel.text;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    
    [self setJddPickerViewHidden:NO];
    [cardInfoPickerView.activityIndicatorView setHidden:NO];
    [cardInfoPickerView.activityIndicatorView startAnimating];    
}

- (void)QueryBankListOperationResult:(NSData *)result{
    if (result) {
        [cardInfoPickerView.activityIndicatorView setHidden:YES];
        
        if ([JddDataParser parseBankListResult:result bankArray:bankArray]) {
            [cardInfoPickerView.pickerView reloadComponent:0];
        }
    }
}

- (IBAction)bankButtonClicked:(id)sender{
    pickerViewMode = PICKERVIEW_MODE_BANK;
    
    if (!citySelected) {
        [JddCommonFunction messageBoxWithMessage:PLEASE_SELECT_CITY];
        return;
    }
    
    JddQueryBankListOperation *operation = [[JddQueryBankListOperation alloc] init];
    operation.delegate = self;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    
    [self setJddPickerViewHidden:NO];
    [cardInfoPickerView.activityIndicatorView setHidden:NO];
    [cardInfoPickerView.activityIndicatorView startAnimating];

}

- (void)jddPickerViewOkButtonClicked{
//        AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
//        [appDelegate.tabBar setUserInteractionEnabled:YES];
//        [appDelegate.navigationController.navigationBar setUserInteractionEnabled:YES];
    
    if ([cardInfoPickerView.pickerView numberOfRowsInComponent:0]>0 ) {
        if ([cardInfoPickerView.pickerView selectedRowInComponent:0] >= [cardInfoPickerView.pickerView numberOfRowsInComponent:0]) {
        [cardInfoPickerView.pickerView selectRow:0 inComponent:0 animated:YES];
    }
    
    UITableViewCell *cell = nil;
    
    UITableViewCell *cell2 = nil;
    cell2 = [selectBankTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
        UITableViewCell *cell3 = nil;
        cell3 = [selectBankTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
        UITableViewCell *cell4 = nil;
        cell4 = [selectBankTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    switch (pickerViewMode) {
        case PICKERVIEW_MODE_PROVINCE:
            cell = [selectBankTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            cell.textLabel.text = [[provinceArray objectAtIndex:[cardInfoPickerView.pickerView selectedRowInComponent:0]] objectForKey:@"Name"];
             cell.textLabel.tag =[[NSString stringWithFormat:@"%@", [[provinceArray objectAtIndex:[cardInfoPickerView.pickerView selectedRowInComponent:0]] objectForKey:@"ID"]] intValue];
            
            province = [NSString stringWithString:cell.textLabel.text];
            [self setJddPickerViewHidden:YES];
            provinceSelected = YES;
            cell3.textLabel.text = @"2.选择城市";
            cell4.textLabel.text = @"3.选择银行";
            citySelected = NO;
            bankSelected = NO;
            break;
        case PICKERVIEW_MODE_CITY:
            cell = [selectBankTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
            cell.textLabel.text = [[cityDictionary objectAtIndex:[cardInfoPickerView.pickerView selectedRowInComponent:0]] objectForKey:@"Name"];
            cell4.textLabel.text = @"3.选择银行";
            city = [NSString stringWithString:cell.textLabel.text];
            [self setJddPickerViewHidden:YES];
            citySelected = YES;
            bankSelected = NO;
            break;
        case PICKERVIEW_MODE_BANK:
            cell = [selectBankTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
            cell.textLabel.text = [[bankArray objectAtIndex:[cardInfoPickerView.pickerView selectedRowInComponent:0]] objectForKey:@"Name"];
            bank = [NSString stringWithString:cell.textLabel.text];
            bankId = [[NSString stringWithFormat:@"%@",
                      [[bankArray objectAtIndex:[cardInfoPickerView.pickerView selectedRowInComponent:0]] objectForKey:@"ID"]] intValue];
        
            if ([bank isEqualToString:@"中国银行"]) {
                cell2.textLabel.text = @"4.请选择支行";
            }else {
                cell2.textLabel.text = @"";
            }
            [self setJddPickerViewHidden:YES];
            bankSelected = YES;
            break;
        case PICKERVIEW_MODE_BRANCH_BANK:
            cell = [selectBankTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
            cell.textLabel.text = [[branchBankArray objectAtIndex:[cardInfoPickerView.pickerView selectedRowInComponent:0]] objectForKey:@"Name"];
            branchBank = [NSString stringWithString:cell.textLabel.text];
            [self setJddPickerViewHidden:YES];
            break;
        default:
            break;
    }
    }
}

- (IBAction)handleSingleTapGesture:(UITapGestureRecognizer*)sender{
    [self.bgScrollView removeGestureRecognizer:sender];
    
    [self.view endEditing:NO];
    
    [self.bgScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isDescendantOfView:self.okButton]) {
        return NO;
    }
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapGesture:)];
    tapGestureRecognizer.delegate = self;
    [self.bgScrollView addGestureRecognizer:tapGestureRecognizer];
    
//    if (textField == self.cardNumberTextField) {
        [self.bgScrollView setContentOffset:CGPointMake(0, 100)
                                   animated:YES];
//    }

    return YES;    
}

- (void)jddPickerViewCancelButtonClicked{
//    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
//    [appDelegate.tabBar setUserInteractionEnabled:YES];
//    [appDelegate.navigationController.navigationBar setUserInteractionEnabled:YES];
    [self setJddPickerViewHidden:YES];
}

- (void)setJddPickerViewHidden:(BOOL)hidden{
    [cardInfoPickerView.pickerView selectRow:0 inComponent:0 animated:YES];

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    
    if (hidden) {

        [cardInfoPickerView setFrame:CGRectMake(0,
                                                [[UIScreen mainScreen] bounds].size.height,
                                                cardInfoPickerView.frame.size.width, 
                                                cardInfoPickerView.frame.size.height)];
        
        pickerViewMode = PICKERVIEW_MODE_NONE;
        [cardInfoPickerView.pickerView reloadComponent:0];
    }
    else {
//        AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
//        [appDelegate.tabBar setUserInteractionEnabled:NO];
//        [appDelegate.navigationController.navigationBar setUserInteractionEnabled:NO];
        
        
        if (SCREEN_HEIGHT > 480) {
            [cardInfoPickerView setFrame:CGRectMake(0,
                                                    SCREEN_HEIGHT - cardInfoPickerView.frame.size.height-60,
                                                    cardInfoPickerView.frame.size.width,
                                                    cardInfoPickerView.frame.size.height)];
        } else {
            [cardInfoPickerView setFrame:CGRectMake(0,
                                                    SCREEN_HEIGHT - cardInfoPickerView.frame.size.height-20,
                                                    cardInfoPickerView.frame.size.width,
                                                    cardInfoPickerView.frame.size.height)];

        }
        
    }
    
    [UIView commitAnimations];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    switch (pickerViewMode) {
        case PICKERVIEW_MODE_PROVINCE:
            return [[provinceArray objectAtIndex:row] objectForKey:@"Name"];
            break;
        case PICKERVIEW_MODE_CITY:
            return [[cityDictionary objectAtIndex:row] objectForKey:@"Name"];
            break;
        case PICKERVIEW_MODE_BANK:
            return [[bankArray objectAtIndex:row] objectForKey:@"Name"];
            break;
        case PICKERVIEW_MODE_BRANCH_BANK:
            return [[branchBankArray objectAtIndex:row] objectForKey:@"Name"];
            break;
        default:
            break;
    }
    return nil;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    switch (pickerViewMode) {
        case PICKERVIEW_MODE_PROVINCE:
            return [provinceArray count];
            break;
        case PICKERVIEW_MODE_CITY:
            return [cityDictionary count];
            break;
        case PICKERVIEW_MODE_BANK:
            return [bankArray count];
            break;
        case PICKERVIEW_MODE_BRANCH_BANK:
            return [branchBankArray count];
            break;
        default:
            break;
    }
    return 0;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

   // [self.navigationItem setTitle:PAGE_BIND_CARD];
        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        [customLab setText:PAGE_BIND_CARD];
        customLab.textAlignment = NSTextAlignmentCenter;
        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;
        
//        //self.navigationItem.hidesBackButton = YES;
    
//        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        backBtn.frame = CGRectMake(0, 0, 12, 19);
//        backBtn.backgroundColor = [UIColor clearColor];
//        //[backBtn setImage:[UIImage imageNamed:@"navbar_back"] forState:UIControlStateNormal];
//        [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
//        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
//        self.navigationItem.leftBarButtonItem = backItem;
    

    
    CGRect rect = [[UIScreen mainScreen] bounds];
    rect.origin.x = rect.size.width/ 2.0;
    rect.origin.y = rect.size.height/ 2.0;
    rect.size.width = rect.size.width;
    rect.size.height = rect.size.height;
    cardInfoPickerView = [JddPickerView getInstanceView];
    [cardInfoPickerView setFrame:rect];
    cardInfoPickerView.delegate = self;
    cardInfoPickerView.pickerView.delegate = self;
    cardInfoPickerView.pickerView.dataSource = self;
    cardInfoPickerView.pickerView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    cardInfoPickerView.pickerView.frame = CGRectMake(0, 40, 320, 100);
    cardInfoPickerView.pickerView.showsSelectionIndicator = YES;
    [self.view addSubview:cardInfoPickerView];
}
- (void)back
{
    [self setJddPickerViewHidden:YES];
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"BindCard"];

    cardNumberTextField.text = @"";
    self.realityName.text = @"";
    cardOwnerLabel.text = @"";
    [bankArray removeAllObjects];
    [cityArray removeAllObjects];
    [provinceArray removeAllObjects];
    [selectBankTableView reloadData];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"BindCard"];
    [MobClick event:@"UserCenter-bindCard"];

    pickerViewMode = PICKERVIEW_MODE_NONE;
    provinceSelected = NO;
    citySelected = NO;
    bankSelected = NO;
//    NSMutableString *temStr =[[NSMutableString alloc] initWithString:[JddUserProfile sharedInstance].realName];
//    if ([temStr length]>=2) {
//        NSMutableString *str = [[NSMutableString alloc] init];
//        for (int i=0; i<[temStr length]-1; i++) {
//            [str appendString:@"*"];
//        }
//        [temStr replaceCharactersInRange:NSMakeRange(1, [temStr length]-1) withString:str];
//    }
//    cardOwnerLabel.text = temStr;
    provinceArray = [NSMutableArray array];
//    cityDictionary = [NSMutableDictionary dictionary];
    cityDictionary = [NSMutableArray array];
    bankArray = [NSMutableArray array];
    branchBankArray = [NSMutableArray array];
}

- (void)viewDidUnload
{
    [self setRealityName:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
